<?php

/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */

class Game_GameController extends Core_Controller_Action_Standard
{

  public function init()
  {
    if( 0 !== ($game_id = (int) $this->_getParam('game_id')) &&
        null !== ($game = Engine_Api::_()->getItem('game', $game_id)) &&
        !Engine_Api::_()->core()->hasSubject() ) {
      Engine_Api::_()->core()->setSubject($game);
    }

    $this->_helper->requireUser();
    $this->_helper->requireSubject('game');
    
    $this->_loadNavigations();
  }

  public function fullscreenAction()
  {
    $this->_helper->layout->setLayout('default-simple');
    
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->game = $game = Engine_Api::_()->core()->getSubject();
  }
  
  
  public function favoriteAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->game = $game = Engine_Api::_()->core()->getSubject();
    
    if ($game->favorites()->isFavorite($viewer))
    {
      $game->favorites()->removeFavorite($viewer);
      $this->view->is_favorite = false;
    }
    else
    {
      $game->favorites()->addFavorite($viewer);
      $this->view->is_favorite = true;
    }

  }
  
  
  public function unfavoriteAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->game = $game = Engine_Api::_()->core()->getSubject();
    
    if ($game->favorites()->isFavorite($viewer))
    {
      $game->favorites()->removeFavorite($viewer);
    }
    
    return $this->_redirectCustom(array('route' => 'game_general', 'action' => 'favorites'));
  }
  
  
  public function successAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->game = $game = Engine_Api::_()->core()->getSubject();
    
    if( !$this->_helper->requireAuth()->setAuthParams(null, null, 'edit')->isValid() ) {
      return;
    }    
  }  
  
  public function editAction()
  {
  	$viewer = Engine_Api::_()->user()->getViewer();
  	$this->view->game = $game = Engine_Api::_()->core()->getSubject('game');
  	
    if( !$this->_helper->requireAuth()->setAuthParams($game, $viewer, 'edit')->isValid() ) {
      return;
    }
    
    $this->view->form = $form = new Game_Form_Game_Edit(array(
      'item' => $game,
    ));

    

    $auth = Engine_Api::_()->authorization()->context;
    $roles = array('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone');
    $auth_keys = array(
      'view' => 'everyone',
      'comment' => 'registered',
      'sign' => 'registered',
    );
    
    // Save game entry
    if( !$this->getRequest()->isPost() )
    {     
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_field = 'auth_'.$auth_key;
        
        foreach( $roles as $i => $role )
        {
          if (isset($form->$auth_field->options[$role]) && 1 === $auth->isAllowed($game, $role, $auth_key))
          {
            $form->$auth_field->setValue($role);
          }
        }
      }
      
      $form->populate($game->toArray());
      return;
    }
        
    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }


    // Process

    // handle save for tags
    $values = $form->getValues();
    $tags = preg_split('/[,]+/', $values['keywords']);
    $tags = array_filter(array_map("trim", $tags));
    
    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try
    {

      $game->setFromArray($values);
      $game->modified_date = date('Y-m-d H:i:s');

      $game->tags()->setTagMaps($viewer, $tags);
      $game->save();

      if (!empty($values['photo']) ) {
        $game->removePhoto();
        $game->setPhoto($form->photo);
      }      

      if (!empty($values['swf_file'])) {
        $game->removeSwf();
        $game->setSwf($form->swf_file);
      }     

      // Save custom fields
      $customfieldform = $form->getSubForm('fields');
      $customfieldform->setItem($game);
      $customfieldform->saveValues();

      // CREATE AUTH STUFF HERE
      $values = $form->getValues();
      
      // CREATE AUTH STUFF HERE
      foreach ($auth_keys as $auth_key => $auth_default)
      {
        $auth_value = isset($values['auth_'.$auth_key]) ? $values['auth_'.$auth_key] : $auth_default;
        $authMax = array_search($auth_value, $roles);
          
        foreach( $roles as $i => $role )
        {
          $auth->setAllowed($game, $role, $auth_key, ($i <= $authMax));
        }
      }
      
      $db->commit();


      $savedChangesNotice = Zend_Registry::get('Zend_Translate')->_("Your changes were saved.");
      $form->addNotice($savedChangesNotice);
      $customfieldform->removeElement('submit');
      
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }

    /*
    $db->beginTransaction();
    try {
      // Rebuild privacy
      $actionTable = Engine_Api::_()->getDbtable('actions', 'activity');
      foreach( $actionTable->getActionsByObject($game) as $action ) {
        $actionTable->resetActivityBindings($action);
      }

      $db->commit();
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    }
		*/
    
    // Redirect
    if( $this->_getParam('ref') === 'profile' ) {
      $this->_redirectCustom($game);
    } else {
      //$this->_redirectCustom(array('route' => 'game_general', 'action' => 'manage'));
    }
  }


  public function deleteAction()
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    $this->view->game = $game = Engine_Api::_()->core()->getSubject('game');

    if( !$this->_helper->requireAuth()->setAuthParams($game, $viewer, 'delete')->isValid()) {
      return;
    }

    $this->view->form = $form = new Game_Form_Game_Delete();
    
    if( !$this->getRequest()->isPost() )
    {
      return;
    }
          
    if( !$form->isValid($this->getRequest()->getPost()) )
    {
      return;
    }    
    
    $db = Engine_Db_Table::getDefaultAdapter();
    $db->beginTransaction();
    try
    {
      $game->delete();
      $db->commit();
    }
    catch( Exception $e )
    {
      $db->rollBack();
      throw $e;
    } 
    
    return $this->_redirectCustom(array('route' => 'game_general', 'action'=>'manage'));
    
  }

  
  protected function _loadNavigations()
  {
    // Get navigation
    $this->view->navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_main');

    // Get quick navigation
    $this->view->quickNavigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_quick');  

    // Get dashboard navigation
    $this->view->dashboardNavigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('game_dashboard');   
  }  
  
}